<!-- 任务列表 -->
<template>
  <div class='classify'>
    <div class="context">
        <div class="left">
           <el-input prefix-icon="el-icon-search" placeholder="输入关键字进行过滤" class="search" v-model="filterText"></el-input>
           <div class="treecon">
               <div class="menubox">
              <div id="menu" v-show="showRight">
                    <div class="menuitem" @click="handleAddcat">
                  添加下级
                </div>
              </div>
              </div>
           <el-tree
                  class="treebox"
                   v-loading="loading"
                  :data="data"
                  :props="defaultProps"
                  :filter-node-method="filterNode"
                  @node-click="handleNodeClick"
                  @node-contextmenu = "handleRightClick"
                  node-key="id"
                  :default-expanded-keys="['CAT0000']"
                  ref="cattree">
                </el-tree>
           </div>
         
        </div>
      <div class="right">
          <div class="title">
             <span class="content_title"><i class="left_line"></i>分类信息</span
                >
          </div>
              <el-form
                :model="category"
                ref="category"
                :rules="rules"
                :inline="true"
                label-width="76px"
                :hide-required-asterisk="true"
                class="right_con"
                label-suffix=":"
              >
                <el-row class="frombox">
                  <el-form-item label="分类ID" prop="ID">
                    <el-input 
                      v-model="category.ID"
                      placeholder="分类ID"
                      clearable
                      size="small"
                      readonly="readonly"
                       :disabled="true"
                    />
                  </el-form-item>
                  <el-form-item label="父级" prop="FatherName">
                    <el-input
                      v-model="category.FatherName"
                      placeholder="父级"
                      clearable
                      size="small"
                      readonly="readonly"
                    />
                  </el-form-item>
                </el-row>
                <el-row class="frombox">
                  <el-form-item label="分类名称" prop="Name">
                    <el-input
                      v-model.trim="category.Name"
                      placeholder="分类名称"
                      clearable
                      size="small"
                      maxlength="150"
                      show-word-limit
                    />
                  </el-form-item>
                  <el-form-item label="分类编号" prop="Code">
                    <el-input
                      v-model.trim="category.Code"
                      placeholder="分类编号"
                      clearable
                      size="small"
                   
                      maxlength="50"
                      show-word-limit
                    />
                  </el-form-item>
                </el-row>
                <el-row class="frombox">
                  <el-form-item label="排序号" prop="Sort">
                    <el-input
                      v-model="category.Sort"
                      placeholder="排序号"
                      clearable
                      size="small"
                      oninput="value=value.replace(/[^\d]/g,'')"
                      maxLength="9"
                    />
                  </el-form-item>
                  <el-form-item label="备注" prop="Summary">
                    <el-input
                      v-model.trim="category.Summary"
                      placeholder="备注"
                      clearable
                      size="small"
                      autosize
                      maxlength="150"
                      show-word-limit
                    />
                  </el-form-item>
                </el-row>
                <el-row class="frombox">
                  <el-form-item label="是否可用" prop="State" size="small">
                    <el-select v-model="category.State" placeholder="请选择">
                      <el-option
                        v-for="item in StateType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-button type="success" class="btncss" icon="el-icon-check" size="small" @click="handleSavecat">保 存</el-button>
                </el-row>
                <!-- <el-button type="success" icon="el-icon-check" size="small" @click="handleSavecat">保 存</el-button> -->
              </el-form>
              <div class="title">
             <span class="content_title"><i class="left_line"></i>属性维护</span>
               <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="small"
                  @click="handleAdd"
                  style="margin-left: 20px"
                  >添 加</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="delproperty"
                  >删 除</el-button
                >
                <el-button
                  type="success"
                  icon="el-icon-unlock"
                  size="small"
                  @click="enable"
                  >启用</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-lock"
                  size="small"
                  @click="disable"
                  >禁 用</el-button
                >
          </div>
                <el-table
                border
                :data="Properties"
                @selection-change="handleSelectionChange"
                :height="tableHeight"
              >
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column
                  label="属性编号"
                  align="center"
                  prop="PropertyID"
                />
                <el-table-column label="属性名称" align="center" prop="Name" />
                <el-table-column
                  label="属性类型"
                  align="center"
                  prop="GroupName"
                />
                <el-table-column label="单位" align="center">
                  <template slot-scope="scope">
                    {{ UnitTypeFilter(scope.row.Unit) }}</template
                  >
                </el-table-column>
                <el-table-column label="值类型" align="center">
                  <template slot-scope="scope">{{
                    ValueTypeFilter(scope.row.ValueType)
                  }}</template>
                </el-table-column>
                <el-table-column label="排序" align="center" prop="Sort" />
                <el-table-column
                  label="是否必填"
                  align="center"
                  key="IsRequired"
                >
                  <template slot-scope="scope">
                    <el-checkbox
                      :checked="scope.row.IsRequired == true"
                      v-model="scope.row.IsRequired"
                      @change="
                        (checked) =>
                          setRequired(
                            scope.row.IsRequired == true,
                            scope.row.ID
                          )
                      "
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="是否启用" align="center" key="State">
                  <template slot-scope="scope">
                    <el-checkbox
                      :checked="scope.row.State == '200'"
                      @change="(checked) => setState(checked, scope.row.ID)"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="备注" align="center" prop="Summary" />
              </el-table>
               <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      id="attribute_dialogue"
      width="65%"
    >
      <!-- 属性添加列表-->
      <div slot="footer" class="dialog-footer">
        <!--搜索条件-->
        <el-form
          :model="search"
          ref="search"
          :inline="true"
          v-show="showSearch"
          label-width="76px"
          style="text-align: left"
        >
          <el-form-item label="属性名称" prop="Name">
            <el-input
              v-model="search.Name"
              placeholder="属性名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="属性类型" prop="GroupName">
            <el-select
              v-model="search.GroupName"
              placeholder="属性类型"
              clearable
              size="medium"
            >
              <el-option
                v-for="dict in GroupOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button
              type="primary"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery()"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!--  height="400" -->
        <el-table 
          ref="tb_prop"
          border
          height="400"
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
         
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="属性编号" align="center" prop="ID" />
          <el-table-column label="属性名称" align="center" prop="Name" />
          <el-table-column label="属性类型" align="center" prop="GroupName" />
          <el-table-column label="单位" align="center">
            <template slot-scope="scope">
              {{ UnitTypeFilter(scope.row.Unit) }}</template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="Sort" />
          <el-table-column label="备注" align="center" prop="Summary" />
        </el-table>
        <div style="text-align: right">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="search.pageIndex"
            :limit.sync="search.pageSize"
            @pagination="getList"
           style="margin:10px 0 25px;"
          />
        </div>
        <el-button size="medium" @click="cancel">取 消</el-button>
        <el-button size="medium" type="primary" @click="submitForm" >确 定</el-button
        >
      </div>
    </el-dialog>
      </div>
    </div>
  
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { getToken } from "@/utils/auth";
import {gettree,Enter,Details,getEnumerate,categoryproplist,GetGroup,RelationProp,SetIsRequired,BootCategoryProperty,StopCategoryProperty,delCategoryProperty,} from "../../api/category.js"

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    //这里存放数据
    return {
      loading: true,
       filterText:'',
        data: [],
        treeID:'',
        nodeData: {},
        level: 0,
        // 选中数组
        ids: [],
         // 用户表格数据
        Properties: null,
        list: null,
        // 弹出层标题
         title: "",
          // 是否显示弹出层
         open: false,
           // 显示搜索条件
        showSearch: true,
         GroupOptions: {}, // 分组
        // 总条数
        total: 0,
        // 右键添加显示
        showRight:false,
        InputTypeOptions: {}, // 单位
         ValueTypeOptions: {}, // 值类型
         defaultProps: {
          children: 'children',
          label: 'label',
          isLeaf: 'isLeaf'
        },
         StateType: [
        { value: 200, label: "是" },
        { value: 400, label: "否" },
      ],
         rules: {
        Name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        FatherName: [{ required: true, message: "请选择一个分类" }],
        Sort: [{ required: true, message: "请输入排序号" }],
      },
       // 查询参数
      category: {
        ID: "",
        FatherID: "",
        FatherName: "",
        Name: "",
        Code: "",
        Sort: "",
        Summary: "",
        CreateDate: "",
        ModifyDate: "",
        State: [],
      },
       //属性查询参数
      search: {
        pageIndex: 1,
        pageSize: 10,
        Name: "",
        GroupName: "",
        ValueType: "",
        State: 200,
      },
      tableHeight: window.innerHeight - 536, //自适应高度
    }
  },
  //监听属性 类似于data概念
  computed: {
     
  },
  //监控data中的数据变化
  watch: {
    filterText(val) {
        this.$refs.cattree.filter(val);
      
      }
  },
  //方法集合
  methods: {
     getTreelist(){
    // 获取tree数据
    gettree().then((data) => {
       this.loading = false;
       this.data = data.data;
    });

   },
    // 点击tree数据
     handleNodeClick(data,node) {
        this.$refs["category"].clearValidate();
         this.treeID = data.id;
          this.nodeData = data.children;
          this.GetNode(data.id);
      
     },
    //  点击右键
     handleRightClick(event,data,node,obj){
       if( node.level <=2){
       this.showRight = false;
      this.showRight= true;
       let menu = document.querySelector("#menu");
      menu.style.left = event.clientX - 150 + 'px';
      menu.style.top = event.clientY + 15 + 'PX';
    
      // 监听鼠标事件 关闭弹框；
       document.addEventListener("click" , this.closeRightMenu,true)
     }
     },
      // 点击任何位置关闭
    closeRightMenu(){
      this.showRight = false;
      document.removeEventListener("click",this.closeRightMenu)
    },
    // 右键添加下级内容
     handleAddcat() {
      if (this.treeID != null && (this.level + 1 != 6 || this.level != 1)) {
        if (this.Properties.length > 0) {
          this.$message.error("此节点已经添加属性,无法添加下级！");
          return;
        } else {
          this.Properties = [];
          this.category = {
            ID: undefined,
            FatherID: this.category.ID,
            FatherName: this.category.Name,
            Name: undefined,
            Code: undefined,
            Sort: 10,
            Summary: undefined,
            State: 200,
          };
        }
      } else {
        this.$message.error("此节点不允许添加");
      }
    },
      // 状态修改
    setRequired(check, id) {
      this.loading = true;
      SetIsRequired(id, check).then((response) => {
        if (response.success) {
          this.msgSuccess("操作成功!");
          this.loading = false;
        } else {
          this.msgError(response.data);
        }
      });
    },
    setState(row, id) {
      this.loading = true;
      if (row) {
        BootCategoryProperty([id]).then((response) => {
          if (response.success) {
            this.msgSuccess("操作成功!");
            this.loading = false;
          } else {
            this.msgError(response.data);
          }
        });
      } else {
        StopCategoryProperty([id]).then((response) => {
          if (response.success) {
            this.msgSuccess("操作成功!");
            this.loading = false;
          } else {
            this.msgError(response.data);
          }
        });
      }
    },
      // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ID);
    },
       /** 查询属性列表 */
    getList() {
      categoryproplist(this.search, this.treeID).then((res) => {
        console.log(res);
        this.list = res.data.Rows;
        this.total = res.data.Total;
      });
    },
     GetNode(id) {
      // this.loading = true;
      Details(id).then((res) => {
        this.category = res.data;
       
        if (this.category.ID != "CAT0000") {
          this.category.FatherName = res.data.Father.Name;
        } else {
          this.category.FatherName = "无";
        }
        // console.log(this.category)
        this.category.FatherID = res.data.Father?.ID;
        // console.log(this.category.FatherID)
        this.Properties = res.data.Properties;
        this.level = res.data.Level;
        this.loading = false;
      });
    },
      // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
      /** 保存分类信息 */
    handleSavecat() {
      if (this.category.ID != "CAT0000") {
        this.$refs["category"].validate((valid) => {
          if (valid) {
            Enter(this.category).then((response) => {
              if (response.success) {
                this.msgSuccess("操作成功!");
                this.getTreelist();
              } else {
                this.msgError("验证失败");
                return false;
              }
            });
          }
        });
      } else {
        this.msgError("无法操作根节点!");
      }
    },
     /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    // 重置
      resetQuery() {
      this.reset("search");
      this.getList();
    },
       // 取消按钮
    cancel() {
      this.open = false;
      this.reset("category");
    },
    // 表单重置
    reset(name) {
      this.$refs[name].resetFields();
    },
     /** 提交按钮 */
    submitForm: function () {
      if (this.treeID == undefined) {
        this.msgError("请选择分类！");
        return;
      }
      if (this.ids.length == 0) {
        this.msgError("请选择属性！");
        return;
      }
      RelationProp(this.treeID, this.ids).then((res) => {
        this.open = false;
        this.GetNode(this.treeID);
      });
    },
    /**属性维护 添加 删除 启用 禁用 */
     handleAdd() {
      if (this.nodeData) {
        this.msgError("请在最下级节点添加！");
        return;
      }
      if (this.treeID == null) {
        this.msgError("无效节点，请重新选择节点！");
        return;
      }
      this.title = "绑定属性";
      this.open = true;
      this.getList();
    },
      delproperty() {
      if (!this.ids.length >= 1) {
        this.msgError("请选择要操作的数据！");
      } else {
        this.$confirm("确定删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          delCategoryProperty(this.ids).then((res) => {
            this.$message.success("操作成功");
            this.Properties = [];
            this.GetNode(this.treeID);
            this.ids = [];
          });
        });
      }
    },
     enable() {
      if (!this.ids.length >= 1) {
        this.msgError("请选择要操作的数据！");
      } else {
        BootCategoryProperty(this.ids).then((res) => {
          this.$message.success("操作成功");
          this.Properties = [];
          this.GetNode(this.treeID);
          this.ids = [];
        });
      }
    },
      disable() {
      if (!this.ids.length >= 1) {
        this.msgError("请选择要操作的数据！");
      } else {
        StopCategoryProperty(this.ids).then((res) => {
          this.$message.success("操作成功");
          this.Properties = [];
          this.GetNode(this.treeID);
          this.ids = [];
        });
      }
    },
      UnitTypeFilter(value) {
      return this.selectDictLabel(this.InputTypeOptions, value);
    },
    ValueTypeFilter(value) {
      return this.selectDictLabel(this.ValueTypeOptions, value);
    },
    

  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
     this.getTreelist();
     getEnumerate(["ValueType", "InputType"]).then((res) => {
      this.ValueTypeOptions = res.data.ValueType;
      this.InputTypeOptions = res.data.InputType;
    });
       GetGroup().then((res) => {
      this.GroupOptions = res.data;
    });
    
    // console.log(getToken());
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
   
  },
  //beforeCreate() {}, //生命周期 - 创建之前
  //beforeMount() {}, //生命周期 - 挂载之前
  //beforeUpdate() {}, //生命周期 - 更新之前
  //updated() {}, //生命周期 - 更新之后
  //beforeDestroy() {}, //生命周期 - 销毁之前
  //destroyed() {}, //生命周期 - 销毁完成
  //activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped lang="scss">
@import './../../assets/reset.css';
.classify{
  box-sizing: border-box;
  padding: 0 20px;
  .context{
    margin: 20px 0;
    width: 100%;
    // height: 100%;
    display: flex;
    .left{
      width: 20%;
      // border: 1px solid #000;
      .search{
        width: 95%;
        margin-bottom: 10px;
      }
      .treebox{
        width: 95%;
        height: calc(100vh - 170px);
        overflow: auto;
      
      }
      .el-tree {
        background: none !important;
        box-sizing: content-box;
         overflow: auto;
}
::v-deep.el-tree {
  width: 100%;
  overflow-x: scroll;
}

::v-deep .el-tree>.el-tree-node {
  display: inline-block;
  min-width: 100%;
}

    }
    .right{
      width: 80%;
      padding: 20px;
      .title{
        padding:0 0 20px 20px;
        border-bottom: 1px solid #EBEEF5;
         .content_title {
          font-weight: bold;
          .left_line {
            display: inline-block;
            width: 3px;
            height: 16px;
            background-color: #286af6;
            vertical-align: middle;
            overflow: hidden;
            margin: -3px 4px 0 0;
          }
     }

      }
      .right_con{
        padding: 20px;
        .frombox{
          width: 100%;
          display: flex;
          .el-form-item{
                  width: 50%;
                }
                .btncss{
                 height: 38px;
                 padding: 0 10px;
                 margin-left: 67px;
                }   
        }

      }
     
     
    }
  }
}
#menu{
 
  position: absolute;
  z-index: 9;

}
.menuitem{
  line-height: 20px;
  text-align: left;
  font-size: 15px;
 padding: 9px 15px;
  border-radius: 5px;
  background-color: #1890ff;
 border: 1px solid #1890ff;
  color: #fff;

}
#attribute_dialogue ::v-deep .el-dialog__body {
  padding: 0;
}
</style>